package game.resource.loader;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import common.Log;

import engine.filesystem.FileScanner;
import engine.filesystem.Resource_A;

public class ResourceLoader {
	public static Resource_A loadResourceXML(String xmlFile, FileScanner scanner) {
		InputStream stream = scanner.openFile(xmlFile);
		if(stream == null) {
			Log.warning("File [" + xmlFile + "] not found.");
			return null;
		}
		Resource_A output = null;
		try {
			XMLReader reader = XMLReaderFactory.createXMLReader();
			SaxStreamHandler handler = new SaxStreamHandler();
			SaxErrorHandler errorHandler = new SaxErrorHandler();
			reader.setContentHandler(handler);
			reader.setErrorHandler(errorHandler);
			reader.parse(new InputSource(stream));
			
			if(handler != null && handler.Builder != null) {
				output = handler.Builder.getResource(scanner);
			}
		} catch (SAXException e) {
			Log.error("File [" + xmlFile + "]");
			Log.error("\t" + e.getMessage());
			//e.printStackTrace();
		} catch (IOException e) {
			Log.error("File [" + xmlFile + "]");
			Log.error("\tError reading from XML input stream : " + e.getMessage());
			//e.printStackTrace();
		}
		try {
			if(stream != null) {
				stream.close();
			}
			
		} catch (IOException e) {
			Log.error("Error closing file stream.");
			e.printStackTrace();
		}
		return output;
	}
}